<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Service;

use Grpc\Base\Common\V1\CommonClient;
use Grpc\Base\Common\V1\CreateUserRequest;
use Grpc\Base\Common\V1\CreateUserResponse;
use Grpc\Base\Common\V1\GetUserRequest;
use Grpc\Base\Common\V1\GetUserResponse;
use Hyperf\Grpc\StatusCode;
use Hyperf\GrpcClient\Exception\GrpcClientException;
use Hyperfx\Framework\Logger\Logx;

class UserService
{
    public function getUser(array $params): array
    {
        /* @var $commonClient CommonClient */
        $commonClient = CommonClient::create();

        $request = new GetUserRequest();
        $request->setUserId($params['user_id']);

        /* @var $response GetUserResponse|string */
        // 这个client是协程安全的，可以复用
        [$response, $status] = $commonClient->GetUser($request);
        if ($status != StatusCode::OK) {
            throw new GrpcClientException($response, $status);
        }

        return [
            'username' => $response->getUsername(),
            'sex' => $response->getSex(),
        ];
    }

    public function createUser(array $params): array
    {
        /* @var $commonClient CommonClient */
        $commonClient = CommonClient::create();

        $request = new CreateUserRequest();
        $request->setUsername($params['username']);
        $request->setName($params['name']);
        $request->setPassword($params['password']);

        /* @var $response CreateUserResponse|string */
        // 这个client是协程安全的，可以复用
        [$response, $status] = $commonClient->CreateUser($request);
        if ($status != StatusCode::OK) {
            throw new GrpcClientException($response, $status);
        }

        return [
            'id' => $response->getId(),
        ];
    }
}
